package com.bishe.serivce.Impl;

import cn.hutool.core.util.StrUtil;
import com.bishe.dao.UserDao;
import com.bishe.pojo.LoginModel;
import com.bishe.pojo.User;
import com.bishe.serivce.IUserService;
import com.bishe.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 用户接口实现
 * @date 2022/03/03 47:03:07
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public LoginModel login(LoginModel loginModel) {
        User user = new SqlQueryUtils<User>(User.class, jdbcTemplate).eq(User::getUserName, loginModel.getUserName()).eq(User::getPassWord, loginModel.getPassWord()).getOne();
        if (user == null){
            throw new EcoBootException("用户名密码错误！");
        }
        String id = user.getId();
        String token = JobUtil.login(user.getPost(), id);

        LoginModel loginModel1 = new LoginModel();
        loginModel1.setType(user.getPost());
        loginModel1.setUserName(user.getUserName());
        loginModel1.setToken(token);
        return loginModel1;
    }

    @Override
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    @Override
    public void updateById(User user) {
        userDao.updateById(user);
    }

    @Override
    public void save(User user) {
        userDao.save(user);
    }

    @Override
    public void addOrUpdate(User user, HttpServletRequest request) {
        //保存
        if (StrUtil.isEmpty(user.getId())){
            User one = new SqlQueryUtils<User>(User.class, jdbcTemplate).eq(User::getUserName, user.getUserName()).getOne();
            if (one!=null){
                throw new EcoBootException("用户名已注册！");
            }
            user.setId(StrUtil.uuid());
            user.setCreateTime(new Date());
            save(user);
            return;
        }
        JobUtil.checkAdminLogin(request,jdbcTemplate);
        //修改
        updateById(user);
    }

    @Override
    public List<User> likeName(String name) {

        return new SqlQueryUtils<User>(User.class, jdbcTemplate).like(User::getNikName, name).getList();
    }
}